package gov.pbc.nn.kjgl.archive.service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.bstek.bdf2.core.controller.IController;
import com.bstek.dorado.core.Configure;

@Component
public class OAUploadController implements IController {

	private static final String URL = "upload.archive";

	public static final String PATH = "";

	@Override
	public String getUrl() {
		return URL;
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String username = request.getParameter("username");
		String cname = request.getParameter("cname");
		String deptId = request.getParameter("deptId");
		String deptName = request.getParameter("deptName");

		MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = mr.getFileMap();
		for (Iterator<String> iter = fileMap.keySet().iterator(); iter.hasNext();) {
			MultipartFile mf = fileMap.get(iter.next());
			String fileName = mf.getOriginalFilename();
			fileName = deptName + "_" + deptId + "_" + cname + "_" + username + "_" + UUID.randomUUID().toString() + "_"
					+ fileName;
			Path target = Paths.get(PATH, fileName);
			Files.copy(mf.getInputStream(), target);
		}
	}

	@Override
	public boolean anonymousAccess() {
		return true;
	}

	@Override
	public boolean isDisabled() {
		return false;
	}

}
